﻿//Copyright 2010 http://tv4home.codeplex.com
//This file is part of TV4Home.Client.QuickEPG.
//TV4Home.Client.QuickEPG is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
//TV4Home.Client.QuickEPG is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//You should have received a copy of the GNU Lesser General Public License along with TV4Home.Client.QuickEPG. If not, see http://www.gnu.org/licenses/.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;

namespace TV4Home.Client.Desktop.QuickEPG
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ITVEInteraction tvWebClient;
        TV4HomeQuickEPGUserControl quickepg = new TV4HomeQuickEPGUserControl();
        private const int WM_SYSCOMMAND = 0x112;
        private readonly static TimeSpan DOUBLE_CLICK_SPAN = TimeSpan.FromMilliseconds(500);
   
        private DateTime _headerLastClick = DateTime.MinValue;

        public MainWindow()
        {
            InitializeComponent();
            grdRoot.Children.Add(quickepg);
        }
        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            chbIsIntranet.IsChecked = Properties.Settings.Default.IsIntranet;

            tbServerName.Text = Properties.Settings.Default.ServerName;
            if (Properties.Settings.Default.ServerName != "")
            {
                GetTVServerData((bool)chbIsIntranet.IsChecked, tbServerName.Text);

            }
            ChangeVisibility(System.Windows.Visibility.Visible);
        }

        private void ChangeVisibility(Visibility visible)
        {
            switch (visible)
            {
                case System.Windows.Visibility.Hidden:
                    brdSettings.Visibility = System.Windows.Visibility.Hidden;
                    lblGroups.Visibility = System.Windows.Visibility.Hidden;
                    lblServerName.Visibility = System.Windows.Visibility.Hidden;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Hidden;
                    chbIsIntranet.Visibility = System.Windows.Visibility.Hidden;
                    btnCheckServer.Visibility = System.Windows.Visibility.Hidden;
                    btnSave.Visibility = System.Windows.Visibility.Hidden;
                    tbServerName.Visibility = System.Windows.Visibility.Hidden;
                    complete_overlay.Visibility = System.Windows.Visibility.Hidden;
                    details_overlay.Visibility = System.Windows.Visibility.Hidden;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Hidden;
                    topRectangle.Visibility = System.Windows.Visibility.Hidden;
                    break;
                case System.Windows.Visibility.Visible:
                    brdSettings.Visibility = System.Windows.Visibility.Visible;
                    lblGroups.Visibility = System.Windows.Visibility.Visible;
                    lblServerName.Visibility = System.Windows.Visibility.Visible;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Visible;
                  //  chbIsIntranet.Visibility = System.Windows.Visibility.Visible;
                    btnCheckServer.Visibility = System.Windows.Visibility.Visible;
                    btnSave.Visibility = System.Windows.Visibility.Visible;
                    tbServerName.Visibility = System.Windows.Visibility.Visible;
                    complete_overlay.Visibility = System.Windows.Visibility.Visible;
                    details_overlay.Visibility = System.Windows.Visibility.Visible;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Visible;
                    topRectangle.Visibility = System.Windows.Visibility.Visible;
                    break;

            }

        }

        private void complete_overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChangeVisibility(System.Windows.Visibility.Hidden);
        }
        private void GetTVServerData(bool IsIntranet, string ServerName)
        {
            try
            {
                if (tvWebClient == null)
                {
                    ConnectToService();
                }
                List<WebChannelGroup> groups = tvWebClient.GetGroups();
                cbChooseGroup.ItemsSource = groups;

                if (Properties.Settings.Default.DefaultGroup != 1)
                {
                    for (int i = 0; i < groups.Count; i++)
                    {

                        if (Properties.Settings.Default.DefaultGroup == groups[i].IdGroup)
                        {
                            cbChooseGroup.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    cbChooseGroup.SelectedIndex = 0;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in GetTVServerData" + ex.ToString());
            }
        }
        public void ConnectToService()
        {
            //Connects to the tv4home webservice by netpipe
            if (Properties.Settings.Default.ServerName != "")
            {
                try
                {
                    if (Properties.Settings.Default.IsIntranet)
                    {
                        try
                        {
                            tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, Properties.Settings.Default.ServerName)));
                        }
                        catch (CommunicationException ex)
                        {
                            tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, Properties.Settings.Default.ServerName)));

                        }
                    }
                    else
                    {

                    }
                }
                catch (Exception ex)
                {
                    //if connection is not possible ask whether it retry or not
                    string sMessageBoxText = "Verbindung konnte nicht hergestellt werden. Erneut versuchen?";
                    string sCaption = "QuickEPG";

                    MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                    MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

                    MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);


                    // Process message box results

                    switch (rsltMessageBox)
                    {

                        case MessageBoxResult.Yes:
                            ConnectToService();

                            break;
                        case MessageBoxResult.No:

                            break;
                    }
                }
            }
        }
        private void btnCheckServer_Click(object sender, RoutedEventArgs e)
        {

            if (tbServerName.Text != "")
            {

                try
                {
                    GetTVServerData((bool)chbIsIntranet.IsChecked, tbServerName.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in ButtonCheckServer" + ex.ToString());
                }
            }
        }
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void RestoreButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        private void btnCloseSettings_Click(object sender, RoutedEventArgs e)
        {
            complete_overlay_MouseLeftButtonDown(this, null);
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.IsIntranet = (bool)chbIsIntranet.IsChecked;
            if (tbServerName.Text != "")
            {
                Properties.Settings.Default.ServerName = tbServerName.Text;
                if (cbChooseGroup.SelectedItem is WebChannelGroup)
                {
                    Properties.Settings.Default.DefaultGroup = ((WebChannelGroup)cbChooseGroup.SelectedItem).IdGroup;
                }
                else
                {

                    Properties.Settings.Default.DefaultGroup = 1;
                }
                Properties.Settings.Default.Save();
                ChangeVisibility(System.Windows.Visibility.Hidden);
                quickepg.FillUserControl();
            }

        }
        private void Header_Drag(object sender, MouseButtonEventArgs e)
        {
            if (DateTime.Now.Subtract(_headerLastClick) <= DOUBLE_CLICK_SPAN)
            {
                this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
            }
            _headerLastClick = DateTime.Now;

            if (Mouse.LeftButton == MouseButtonState.Pressed) this.DragMove();
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
